package com.jc.service.api.appgame;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.Base64Util;
import com.jc.common.util.CommonStr;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.framework.enums.Conclusion;
import com.jc.framework.enums.LogType;
import com.jc.framework.util.PropertyPlaceholder;
import com.jc.framework.util.SpringUtils;
import com.jc.framework.web.ResponseResultModel;
import com.jc.service.api.BaseDual;
import com.jc.service.api.appgame.model.Param;
import com.jc.service.apilog.ApiLogService;
import com.jc.service.chain.ChainResult;
import com.jc.service.gameuser.GameUserService;
import com.jc.service.userorder.UserOrderService;
import com.jc.service.uservrtaddress.UserVrtAddressService;
import com.jc.service.vrt.VrtService;

public class query extends BaseDual<Param>{
	
	
	private GameUserService gameUserService = SpringUtils.getBean(GameUserService.class);
	private UserVrtAddressService userVrtAddressService = SpringUtils.getBean(UserVrtAddressService.class);
	private VrtService vrtService = SpringUtils.getBean(VrtService.class);
	private UserOrderService userOrderService = SpringUtils.getBean(UserOrderService.class);
	private ApiLogService apiLogService = SpringUtils.getBean(ApiLogService.class);
	final String currencyName = (String) PropertyPlaceholder.getProperty("transfer.currency.name");
	
	
	
	public ResponseEntity<?> dual(JSONObject data) {
		
		Param param = getData(data);
		String jsonData = null;
		try {
			if(StringUtils.isBlank(param.getEncrypt())) {
				throw new BaseServiceException("参数错误,请重试!");
			}
			jsonData = Base64Util.decode(param.getEncrypt());
			JSONObject user = JSONObject.parseObject(jsonData);
			String out_user_id = user.getString("userId");
			ChainResult result = userOrderService.queryBalance(Long.valueOf(out_user_id), currencyName);
			if(result == null || !StringUtils.equals(result.getReturn_code(), CommonStr.SUCCESS) ) {
				
				throw new BaseServiceException("VRT链上查询错误! " + (result == null ? "" : result.getReturn_msg()));
			}
			HashMap<String, Object> retMap = new HashMap<String, Object>();
			retMap.put("balance", result.getBalance());
			return new ResponseEntity<>(new ResponseResultModel<Map<String,Object>>(retMap),HttpStatus.OK);
			 
		} catch (Exception e) {
			String error = e.getMessage();
			if(e.getMessage().length() > 150) {
				error = StringUtils.substring(e.getMessage(), 0, 150);
			}
			getLoger().error("查询异常 : 原因 : {} , {}", e.getMessage(), e);
			
			apiLogService.addApiLog(LogType.APP_GAME_REQUEST_LOGIN, jsonData , Conclusion.FAIL, "系统异常", error);
			
			return new ResponseEntity<>(new ResponseResultModel<>("查询异常, 发生系统错误"), HttpStatus.OK);
		}

	}
}
